﻿using Sustainalytics.AwsS3.Client;
using Sustainalytics.Entities;
using Sustainalytics.Synchronization.Interface;
using Sustainalytics.Utils.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Sustainalytics.ClientDW.Synchronization
{
    public class S3CleanupSyncStep : ISyncStep
    {
        public SyncStepOrder ExecutionOrder => SyncStepOrder.CleanupS3;

        public SyncContext Start(SyncContext syncContext)
        {
            var connectionString = syncContext.GAConnectionStrings;
            var finalLetter = string.Empty;
            if (connectionString["ClientDW"].Contains("ClientDW_A"))
                finalLetter = "_A";
            if (connectionString["ClientDW"].Contains("ClientDW_B"))
                finalLetter = "_B";

            var s3ClientSettings = new S3ClientSettings
            {
                AccessKey = SettingsHelper.Read("accesKeyId", "AKIAJKGZZMOFAVOVLHJA"),
                SecretAccessKey = SettingsHelper.Read("awsSecretKey", "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"),
                ServiceEndPoint = SettingsHelper.Read("s3ServiceEndPoint", "https://s3-eu-west-1.amazonaws.com/")
            };

            var bucketName = SettingsHelper.Read("s3bucket", "dev-globalaccess-europe");
            var foldersToDelete = new List<string>()
            {
                string.Concat("ComprehensiveReport", finalLetter),
                string.Concat("SummaryComprehensiveReport", finalLetter),
                string.Concat("CoreReport", finalLetter),
                string.Concat("SummaryCoreReport", finalLetter),
                string.Concat("ControversyReport", finalLetter),
                string.Concat("PregeneratedReports", finalLetter),
                string.Concat("RiskRatingsReport", finalLetter),
                string.Concat("SummaryRiskRatingsReport", finalLetter),
                string.Concat("TearSheetReport", finalLetter),
                string.Concat("CorporateGovernanceCompanyReport", finalLetter)
            };

            var hasChanges = (syncContext.PreviousChanges.ToList()).Exists(x => x.AffectedKey == "Global Compact Documents Updated");
            if (hasChanges)
            {
                foldersToDelete.Add(ReportType.GlobalCompactComplianceReport.ToString());
            }

            try
            {
                using (var s3client = new S3Client(s3ClientSettings))
                {
                    foldersToDelete.ForEach(s3Folder =>
                    {
                        syncContext.Log(string.Format("Deleting {0}", s3Folder));

                        s3client.DeleteBulk(bucketName, s3Folder);
                    });
                }
            }
            catch (Exception ex)
            {
                syncContext.Log(string.Format("S3CleanupSyncStep exception: {0}. Stack trace {1}", ex.Message, ex.StackTrace));
            }
            return syncContext;
        }
    }
}
